package com.yuan.algorithms.arithmetic_1;

/*
 * 顺序存储结构实现堆栈
 */
public class StackSLinked {
	private final int LEN = 10;// 数组的默认大小
	private Object[] elements;
	private int top;// 栈顶指针

	public StackSLinked() {
		top = -1;
		elements = new Object[LEN];
	}

	/**
	 * 返回堆栈大小
	 * 
	 */
	public int getSize() {
		return top + 1;
	}

	/**
	 * 判断堆栈是否为空
	 * 
	 */
	public boolean isEmpty() {
		return top < 0;
	}

	/**
	 * 数据入栈
	 * 
	 * @param e
	 */
	public void push(Object e) {
		// 判断堆栈元素是否满了
		if (getSize() >= elements.length) {
			expandSpace();
		}
		elements[++top] = e;
	}

	/*
	 * 扩充堆栈大小
	 */
	private void expandSpace() {
		Object[] a = new Object[elements.length * 2];
		for (int i = 0; i < elements.length; i++) {
			a[i] = elements[i];
		}
		elements = a;
	}

	/**
	 * 栈顶元素出栈
	 * 
	 * @throws RuntimeException
	 */
	public Object pop() throws RuntimeException {
		if (getSize() < 1) {
			throw new RuntimeException("错误，堆栈为空。");
		}
		Object obj = elements[top];
		elements[top--] = null;// 删除元素并将栈顶指针下移
		return obj;
	}

	/**
	 * 取栈顶元素（不删除元素）
	 * 
	 * @throws RuntimeException
	 */
	public Object peek() throws RuntimeException {
		if (getSize() < 1) {
			throw new RuntimeException("错误，堆栈为空。");
		}
		return elements[top];
	}
}
